/*
 * BangoStorage.cpp
 *
 *  Created on: 7 Jan 2013
 */
#include "BangoStorage.h"
#include "BangoConstants.h"


BangoStorage::BangoStorage(QObject *parent) : QObject(parent)
{
	_databaseName = BangoConstants::GetInstance()->DATABASE_NAME;

	_databaseVersion = BangoConstants::GetInstance()->DATABASE_VERSION;

	LoadDatabase();
}

BangoStorage::~BangoStorage()
{
	if(dbBango.isOpen())
	{
		dbBango.close();
	}
}


bool BangoStorage::LoadDatabase()
{
	qDebug() << __PRETTY_FUNCTION__;
	bool success;
	if(CopyDbToDataFolder())
	{
		_databaseNameWithPath = "data/" + _databaseName;

		dbBango = QSqlDatabase::addDatabase("QSQLITE", "database_helper_connection");
		dbBango.setDatabaseName(_databaseNameWithPath);

		if(!dbBango.isValid()){
			qWarning() << "Could not set database name, probably due to an invalid driver";
			return false;
		}
		dbBango.open();
		if(dbBango.isOpen() != true){
			qWarning() << "Could not open database";
			success = false;
		}
		else{
			CreateTables();
			qDebug() << "Database open" << _databaseNameWithPath << " Success";
			success = true;
		}

	}
	else {
		success = false;
	}
	return success;

}

QString BangoStorage::CompileQueryStatement(const QString tableName, const QString queryText)
{
	QString table = tableName + "_" + QString::number(_databaseVersion);
	QString placeHolderText = BangoConstants::GetInstance()->DATABASE_TABLE_PLACEHOLDER;
	QString queryString = queryText;
	return queryString.replace(placeHolderText, table);
}

QString BangoStorage::CompileCreateTableQuery(const QString tableName, const QString queryText)
{
	QString query;
	QString table = tableName + "_" + QString::number(_databaseVersion);
	QString tableCreate = queryText;
	QString placeholder = BangoConstants::GetInstance()->DATABASE_TABLE_PLACEHOLDER;
	query = tableCreate.replace(placeholder, table);
	return query;
}

QString BangoStorage::ProfileTableQuery()
{
	QString profileQuery = CompileCreateTableQuery(BangoConstants::GetInstance()->DATABASE_TABLENAMEPROFILE, BangoConstants::GetInstance()->DATABASE_TABLECREATEPROFILE);
	return profileQuery;
}
QString BangoStorage::EventTableQuery()
{
	QString eventTableQuery = CompileCreateTableQuery(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENT, BangoConstants::GetInstance()->DATABASE_TABLECREATEEVENT);
	return eventTableQuery;

}

QString BangoStorage::EventParameterTableQuery()
{
	QString eventParameterTableQuery = CompileCreateTableQuery(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENTPARAMETER, BangoConstants::GetInstance()->DATABASE_TABLECREATEEVENTPARAMETER);
	return eventParameterTableQuery;
}


void BangoStorage::CreateTables()
{
	QSqlQuery query(dbBango);
	query.exec(ProfileTableQuery());
	query.exec(EventTableQuery());
	query.exec(EventParameterTableQuery());
	CompactDatabase();
}

void BangoStorage::DropTables()
{
	SqlDataAccess sqlDataAccess(_databaseNameWithPath);
	QVariantList sqlData;
	sqlData = sqlDataAccess.execute(BangoConstants::GetInstance()->DATABASE_SELECTTABLES).value<QVariantList>();
	if(sqlDataAccess.hasError()) {
		DataAccessError err = sqlDataAccess.error();
		qWarning() << "SQL error: type=" << err.errorType() << ": " << err.errorMessage();
	}
	QSqlQuery query(dbBango);
	for (int i = 0; i <= sqlData.size(); i++)
	    {
	        qDebug() << sqlData.value(i);
	        query.exec("DROP TABLE IF EXISTS [" + sqlData.value(i).toString() + "]");

	    }
}



void BangoStorage::CompactDatabase() const
{
	QSqlQuery query(dbBango);
	query.exec("VACUUM;");
}

bool BangoStorage::CopyDbToDataFolder()
{
	qDebug() << __PRETTY_FUNCTION__;
	QString datafolder = QDir::homePath();
	QString newFileName = datafolder + "/" + _databaseName;
	QFile newFile(newFileName);

	if(!newFile.exists())
	{
		QString appFolder(QDir::homePath());
		appFolder.chop(4);
		QString originalFileName = appFolder + "app/native/assets/sql" + _databaseName;
		QFile originalFile(originalFileName);

		if(originalFile.exists())
		{
			QFileInfo fileInfo(newFileName);
			QDir().mkpath(fileInfo.dir().path());
			if(!originalFile.copy(newFileName)){
				qDebug() <<"Failed to copy file to path: " << newFileName;
			}
			else{
				qDebug() << "Failed to copy file database file does not exist";
			}
		}
	}
	_databaseNameWithPath = newFileName;

	return true;
}


void BangoStorage::CloseConnection()
{
	if(dbBango.isOpen() && !_openLogProfile && !_openUpdateProfileLocation && !_openLogEvent && !_openProfilesForPost && !_openEventsForPost && !_openDeleteEventsPosted)
	{
		dbBango.close();
	}
}

void BangoStorage::CloseDatabase(bool ignorePersistConnection)
{
	if(ignorePersistConnection || !PersistDatabaseConnection())
	{
		CloseConnection();
	}
}



void BangoStorage::LogProfile(BangoProfile bangoProfile)
{
	LogProfile(bangoProfile.SDKType(), bangoProfile.SDKVersion(), bangoProfile.ApplicationID(), bangoProfile.ApplicationType(), bangoProfile.ApplicationChannel(), bangoProfile.ApplicationVersion(), bangoProfile.UserID(),
			bangoProfile.SessionRestartTime(), bangoProfile.ConnectionType(), bangoProfile.IsRoaming(), bangoProfile.LocationSource(), bangoProfile.LocationAltitude(), bangoProfile.LocationLatitude(), bangoProfile.LocationLongitude(),
			bangoProfile.LocationAccuracy(),bangoProfile.Operator(), bangoProfile.OperatorName(), bangoProfile.OperatorCountryISO(), bangoProfile.SimOperator(), bangoProfile.SimCardSerial(),
			bangoProfile.Device(), bangoProfile.Model(), bangoProfile.HardwareId(), bangoProfile.Version(), bangoProfile.Pin(), bangoProfile.OperatorConnectionType());
}

void BangoStorage::LogProfile(int sdkType, QString sdkVersion, QString applicationId, QString applicationType, QString applicationChannel, QString applicationVersion, QString userId, int sessionRestartTime,
		int connectionType, bool isRoaming, QString locationSource, double locationAltitude, double locationLatitude, double locationLongitude,
		float locationAccuracy, QString mOperator, QString operatorName, QString operatorCountryIso, QString simOperator, QString simCardSerial, QString device, QString model, QString hardwareId,
		QString version, QString pin, QString operatorConnectionType)
{
	qDebug() << __PRETTY_FUNCTION__;

	if(dbBango.isOpen()){
		QSqlQuery sqlQuery(dbBango);

		int isRoamingInt = isRoaming ? 1 : 0;

		if(applicationId.isNull()) {
			applicationId = "";
		}
		if(applicationType.isNull()) {
			applicationType = "";
		}
		if(applicationChannel.isNull()) {
			applicationChannel = "";
		}
		if(applicationVersion.isNull()) {
			applicationVersion = "";
		}
		if(userId.isNull()) {
			userId = "";
		}
		if(locationSource.isNull()) {
			locationSource = "";
		}
		if(mOperator.isNull()) {
			mOperator = "";
		}
		if(operatorCountryIso.isNull()) {
			operatorCountryIso = "";
		}
		if(simOperator.isNull()) {
			simOperator = "";
		}
		if(simCardSerial.isNull()){
			simCardSerial = "";
		}
		if(device.isNull()){
			device = "";
		}
		if(model.isNull()){
			model = "";
		}
		if(hardwareId.isNull()){
			hardwareId = "";
		}
		if(version.isNull()){
			version = "";
		}
		if(pin.isNull()){
			pin = "";
		}

		_openLogProfile = true;

		//prepare the SQL Statement
		QString query;
		query = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEPROFILE, BangoConstants::GetInstance()->DATABASE_CREATEPROFILE);


		sqlQuery.prepare(query);
		sqlQuery.bindValue(0, sdkType);
		sqlQuery.bindValue(1, sdkVersion);
		sqlQuery.bindValue(2, applicationId);
		sqlQuery.bindValue(3, applicationType);
		sqlQuery.bindValue(4, applicationChannel);
		sqlQuery.bindValue(5, applicationVersion);

		sqlQuery.bindValue(6, userId);

		sqlQuery.bindValue(7, sessionRestartTime);
		sqlQuery.bindValue(8, connectionType);
		sqlQuery.bindValue(9, isRoamingInt);

		sqlQuery.bindValue(10, locationSource);
		sqlQuery.bindValue(11, locationAltitude);
		sqlQuery.bindValue(12, locationLatitude);
		sqlQuery.bindValue(13, locationLongitude);
		sqlQuery.bindValue(14, locationAccuracy);

		sqlQuery.bindValue(15, mOperator);
		sqlQuery.bindValue(16, operatorName);
		sqlQuery.bindValue(17, operatorCountryIso);
		sqlQuery.bindValue(18, simOperator);
		sqlQuery.bindValue(19, simCardSerial);
		sqlQuery.bindValue(20, device);
		sqlQuery.bindValue(21, model);
		sqlQuery.bindValue(22, hardwareId);
		sqlQuery.bindValue(23, version);
		sqlQuery.bindValue(24, pin);

		sqlQuery.bindValue(25, operatorConnectionType);
		sqlQuery.bindValue(26, 0);

		sqlQuery.exec();

		const QSqlError err = sqlQuery.lastError();
		if(err.isValid()) {
			qWarning() << "Error executing SQL statement: " << query << ". ERROR: " << err.text();
		} else {
			if(sqlQuery.lastInsertId().isValid()){
				_profileId = sqlQuery.lastInsertId().toInt();

			}
		}
	}

	_openLogProfile = false;
	dbBango.close();

}

void BangoStorage::UpdateProfileLocation(QString locationSource, double locationLatitude, double locationLongitude, double locationAltitude, float locationAccuracy)
{
	qDebug() << __PRETTY_FUNCTION__;
	QString query;
	query = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEPROFILE, BangoConstants::GetInstance()->DATABASE_UPDATEPROFILELOCATION);


	_openUpdateProfileLocation = true;
	dbBango.open();
	QSqlQuery sqlQuery(dbBango);


	sqlQuery.prepare(query);
	sqlQuery.bindValue(":locationSource", locationSource);
	sqlQuery.bindValue(":locationLatitude", locationLatitude);
	sqlQuery.bindValue(":locationLongitude", locationLongitude);
	sqlQuery.bindValue(":locationAltitude", locationAltitude);
	sqlQuery.bindValue(":locationAccuracy", locationAccuracy);
	sqlQuery.bindValue(":id", QString::number(_profileId));
	sqlQuery.exec();

	const QSqlError err = sqlQuery.lastError();
	if(err.isValid()) {
		qWarning() << "Error executing SQL statement: " << query << ". ERROR: " << err.text();
	}
	else {
		_openLogProfile = false;
		dbBango.close();
	}
}

int BangoStorage::LogEvent(BangoEvent bangoEvent)
{
	return LogEvent(bangoEvent.ConnectionType(), bangoEvent.OperatorConnectionType(), bangoEvent.ErrorLevel(), bangoEvent.EventName(), bangoEvent.EventDetail(), bangoEvent.EventValue(), bangoEvent.ErrorID(), bangoEvent.EventTime(), bangoEvent.EventLocalTime(), bangoEvent.EventParamters());
}

int BangoStorage::LogEvent(int connectionType, QString operatorConnectionType, int errorLevel, QString eventName, QString eventDetail, QString eventValue, QString errorId, QDateTime eventTime, QDateTime eventLocalTime, QVector<BangoNameValuePair> eventParameters)
{
	qDebug() << __PRETTY_FUNCTION__;

	int eventId = -1;
	if(eventName.isNull()) {
		eventName = "";
	}
	if(eventDetail.isNull()) {
		eventDetail = "";
	}
	if(eventValue.isNull()) {
		eventValue = "";
	}
	if(errorId.isNull()) {
		errorId = "";
	}
	dbBango.open();
	if(dbBango.isOpen()) {
		QSqlQuery sqlQuery(dbBango);
		QString query = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENT, BangoConstants::GetInstance()->DATABASE_CREATEEVENT);

		qDebug() <<	sqlQuery.prepare(query);

		sqlQuery.bindValue(0, _profileId);
		sqlQuery.bindValue(1, eventName);
		sqlQuery.bindValue(2, eventDetail);
		sqlQuery.bindValue(3, eventValue);
		sqlQuery.bindValue(4, errorId);
		sqlQuery.bindValue(5, eventTime);
		sqlQuery.bindValue(6, eventLocalTime);
		sqlQuery.bindValue(7, connectionType);
		sqlQuery.bindValue(8, operatorConnectionType);
		sqlQuery.bindValue(9, errorLevel);
		sqlQuery.bindValue(10, 0);
		qDebug() << "Bound Values: " << sqlQuery.boundValues();
		sqlQuery.exec();

		const QSqlError err = sqlQuery.lastError();
		if(err.isValid()) {
			qWarning() << "Error executing SQL statement: " << query << ". ERROR: " << err.text();
		} else {
			if(sqlQuery.lastInsertId().isValid()){
				eventId = sqlQuery.lastInsertId().toInt();
				_openLogEvent = false;

				dbBango.close();
				LogEventParameter(eventId, eventParameters);
			}
		}



	}
	return eventId;
}

void BangoStorage::LogEventParameter(int eventId, QVector<BangoNameValuePair> eventParameters)
{
	qDebug() << __PRETTY_FUNCTION__;
	BangoNameValuePair eventParameter;
	QString eventParameterName;
	QString eventParameterValue;
	if(eventParameters.size() > 0){
	QVectorIterator<BangoNameValuePair>iter(eventParameters);
		while(iter.hasNext()) {
			eventParameter = iter.next();
			eventParameterName = eventParameter.GetName();
			eventParameterValue = eventParameter.GetValue();

			if(eventParameterName.isNull()) {
				eventParameterName = "";
			}

			if(eventParameterValue.isNull()) {
				eventParameterValue = "";
			}
			dbBango.open();
			if(dbBango.isOpen()){
				QSqlQuery paramQuery(dbBango);

				QString queryString = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENTPARAMETER, BangoConstants::GetInstance()->DATABASE_CREATEEVENTPARAMETER);
				qDebug() << paramQuery.prepare(queryString);

				paramQuery.bindValue(0, eventId);
				paramQuery.bindValue(1, eventParameterName);
				paramQuery.bindValue(2, eventParameterValue);
				qDebug() << "Bound Values: " << paramQuery.boundValues();
				paramQuery.exec();

				const QSqlError err = paramQuery.lastError();
				if(err.isValid()) {
					qWarning() << "Error executing SQL statement: " << queryString << ". ERROR: " << err.text();
				}else {

					dbBango.close();
					qDebug()<< "insert success";
					if(paramQuery.isActive()){
						paramQuery.finish();
					}
				}
			}

		}
	}
	else{
		qDebug() << "no parameters";
	}

}


QVector<BangoProfile> BangoStorage::GetProfilesForPost(bool notCurrentProfile)
{
	qDebug() << __PRETTY_FUNCTION__;
	int notProfileId = 0;
	QVector<BangoProfile> returnValue;
	BangoProfile bangoProfile;

	if(notCurrentProfile) {
		notProfileId = _profileId;
	}

	_openProfilesForPost = true;
	dbBango.open();

	if(dbBango.isOpen()) {

		QSqlQuery profileQuery(dbBango);

		QString profileQueryString = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEPROFILE,BangoConstants::GetInstance()->DATABASE_SELECTPOSTPROFILES);
		qDebug() << profileQuery.prepare(profileQueryString);
		profileQuery.bindValue(":id", QString::number(notProfileId));
		qDebug() << "Bound Id Value: " << profileQuery.boundValues();

		profileQuery.exec();

		while(profileQuery.next()){
			bangoProfile.ProfileID(profileQuery.value(0).toInt());
			bangoProfile.SDKType(profileQuery.value(1).toInt());
			bangoProfile.SDKVersion(profileQuery.value(2).toString());
			bangoProfile.ApplicationID(profileQuery.value(3).toString());
			bangoProfile.ApplicationType(profileQuery.value(4).toString());
			bangoProfile.ApplicationChannel(profileQuery.value(5).toString());
			bangoProfile.ApplicationVersion(profileQuery.value(6).toString());
			bangoProfile.UserID(profileQuery.value(7).toString());
			bangoProfile.SessionRestartTime(profileQuery.value(8).toInt());
			bangoProfile.ConnectionType(profileQuery.value(9).toInt());
			bangoProfile.IsRoaming(profileQuery.value(10).toInt() == 0 ? false : true);
			bangoProfile.LocationSource(profileQuery.value(11).toString());
			bangoProfile.LocationAltitude(profileQuery.value(12).toDouble());
			bangoProfile.LocationLatitude(profileQuery.value(13).toDouble());
			bangoProfile.LocationLongitude(profileQuery.value(14).toDouble());
			bangoProfile.LocationAccuracy(profileQuery.value(15).toFloat());
			bangoProfile.Operator(profileQuery.value(16).toString());
			bangoProfile.OperatorName(profileQuery.value(17).toString());
			bangoProfile.OperatorCountryISO(profileQuery.value(18).toString());
			bangoProfile.SimOperator(profileQuery.value(19).toString());
			bangoProfile.SimCardSerial(profileQuery.value(20).toString());
			bangoProfile.Device(profileQuery.value(21).toString());
			bangoProfile.Model(profileQuery.value(22).toString());
			bangoProfile.HardwareId(profileQuery.value(23).toString());
			bangoProfile.Version(profileQuery.value(24).toString());
			bangoProfile.Pin(profileQuery.value(25).toString());
			bangoProfile.OperatorConnectionType(profileQuery.value(26).toString());

			returnValue.append(bangoProfile);

		}

			const QSqlError err = profileQuery.lastError();
			if(err.isValid()) {

				qWarning() << "Error executing SQL statement: " << profileQueryString << ". ERROR: " << err.text();
				return returnValue;
			}
			else {
				dbBango.close();
			}

	}
	return returnValue;

}

QVector<BangoEvent> BangoStorage::GetEventsForPost(int profileId)
{
	qDebug() << __PRETTY_FUNCTION__;
	QVector<BangoEvent> returnValue;
	BangoEvent bangoEvent;
	QVector<BangoNameValuePair> bangoEventParameters;


	dbBango.open();
	if(dbBango.isOpen()){

		_openEventsForPost = true;
		QSqlQuery sqlEventQuery(dbBango);
		QSqlQuery sqlEventParameterQuery(dbBango);


		QString eventQuery = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENT, BangoConstants::GetInstance()->DATABASE_SELECTPOSTEVENTS);
		QString eventParameterQuery = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENTPARAMETER, BangoConstants::GetInstance()->DATABASE_SELECTPOSTEVENTPARAMETERS);
		qDebug() << sqlEventQuery.prepare(eventQuery);

		sqlEventQuery.bindValue(":id", profileId);
		qDebug() << "Bound event Id Value: " << sqlEventQuery.boundValues();

		sqlEventQuery.exec();


		while(sqlEventQuery.next()){

			bangoEvent.EventID(sqlEventQuery.value(0).toInt());
			bangoEvent.ProfileID(sqlEventQuery.value(1).toInt());
			bangoEvent.EventName(sqlEventQuery.value(2).toString());
			bangoEvent.EventDetail(sqlEventQuery.value(3).toString());
			bangoEvent.EventValue(sqlEventQuery.value(4).toString());
			bangoEvent.ErrorID(sqlEventQuery.value(5).toString());
			bangoEvent.EventTime(sqlEventQuery.value(6).toDateTime());
			bangoEvent.EventLocalTime(sqlEventQuery.value(7).toDateTime());
			bangoEvent.ConnectionType(sqlEventQuery.value(8).toInt());
			bangoEvent.OperatorConnectionType(sqlEventQuery.value(9).toString());
			bangoEvent.ErrorLevel(sqlEventQuery.value(10).toInt());
			bangoEvent.EventParamters();


				qDebug() << sqlEventParameterQuery.prepare(eventParameterQuery);

				sqlEventParameterQuery.bindValue(":id", bangoEvent.EventID());
				qDebug() << "Bound eventIds Value: " << sqlEventParameterQuery.boundValues();

				sqlEventParameterQuery.exec();

				while(sqlEventParameterQuery.next()){

					bangoEventParameters.append(BangoNameValuePair(sqlEventParameterQuery.value(2).toString(),sqlEventParameterQuery.value(3).toString()));
				}
				bangoEvent.EventParameters(bangoEventParameters);

				returnValue.append(bangoEvent);
			}

			const QSqlError err = sqlEventQuery.lastError();
			const QSqlError error = sqlEventParameterQuery.lastError();
			if(err.isValid()) {

				qWarning() << "Error executing SQL statement: " << eventQuery << ". ERROR: " << err.text();
				return returnValue;
			}
			else {

				dbBango.close();
			}
			if(error.isValid()){
				qWarning() << "Error executing SQL statement: " << eventParameterQuery << ". ERROR: " << error.text();
				return returnValue;
			}
			else {
				dbBango.close();
			}
		}

		return returnValue;
}




bool BangoStorage::DeleteOrphannedRecords()
{
	qDebug() << __PRETTY_FUNCTION__;
	bool returnValue = false;
	dbBango.open();
	if(dbBango.isOpen()) {
		QString deleteOrphannedEventString = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENT, BangoConstants::GetInstance()->DATABASE_DELETEORPHANEVENT);
		QString joinPlaceholder = BangoConstants::GetInstance()->DATABASE_TABLE_JOINPLACEHOLDER;
		QString profileTable = BangoConstants::GetInstance()->DATABASE_TABLENAMEPROFILE + "_" + QString::number(_databaseVersion);
		deleteOrphannedEventString = deleteOrphannedEventString.replace(joinPlaceholder, profileTable);

		QString deleteOrphannedEventParamString = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENTPARAMETER, BangoConstants::GetInstance()->DATABASE_DELETEORPHANEVENTPARAMETER);
		QString eventTable = BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENT + "_" + QString::number(_databaseVersion);
		deleteOrphannedEventParamString = deleteOrphannedEventParamString.replace(joinPlaceholder, eventTable);

		dbBango.transaction();
		QSqlQuery query(dbBango);
		query.exec(deleteOrphannedEventString);
		query.exec(deleteOrphannedEventParamString);

		const QSqlError err = query.lastError();
		if(err.isValid()) {
			qWarning() << "Error in delete transaction: " << query.lastQuery() << ". ERROR: " << err.text();
			dbBango.rollback();
			returnValue = false;
		}
		else
		{
			dbBango.commit();
			returnValue = true;
		}
		if(dbBango.isOpen()){
			dbBango.close();
		}
	}
	return returnValue;
}

bool BangoStorage::UpdateEventsPosted(int profileId)
{
	qDebug() << __PRETTY_FUNCTION__;
	bool returnValue = false;
	_openEventsPosted = true;

	QString updateQueryString = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENT, BangoConstants::GetInstance()->DATABASE_UPDATEEVENTPOSTED + QString::number(profileId));
	QString updateProfileString = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEPROFILE, BangoConstants::GetInstance()->DATABASE_UPDATEPROFILEPOSTED + QString::number(profileId));

	dbBango.open();
	if(dbBango.isOpen()){

		dbBango.transaction();
		QSqlQuery query(dbBango);
		query.exec(updateQueryString);
		query.exec(updateProfileString);

		const QSqlError err = query.lastError();

		if(err.isValid()) {
			qWarning() << "Error in update Transaction: " << query.lastQuery() << ". ERROR: " << err.text();
			dbBango.rollback();
			returnValue = false;
		}
		else
		{
			dbBango.commit();
			returnValue = true;
		}
	}
	if(dbBango.isOpen()){
		dbBango.close();
	}
	return returnValue;

}

bool BangoStorage::DeleteEventsPosted(int profileId)
{
	qDebug() << __PRETTY_FUNCTION__;
	bool returnValue = false;
	QString eventTableName = BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENT + "_" + QString::number(_databaseVersion);
	QString profileTableName = BangoConstants::GetInstance()->DATABASE_TABLENAMEPROFILE + "_" + QString::number(_databaseVersion);
	QString parameter1Placeholder = BangoConstants::GetInstance()->DATABASE_PARAMETER1_PLACEHOLDER;

	QString deleteEventParameterString;
	QString deleteEventString;
	QString deleteProfileString;
	QString joinPlaceholder = BangoConstants::GetInstance()->DATABASE_TABLE_JOINPLACEHOLDER;

	deleteEventParameterString = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENTPARAMETER, BangoConstants::GetInstance()->DATABASE_DELETEEVENTPARAMETER);
	deleteEventParameterString = deleteEventParameterString.replace(joinPlaceholder, eventTableName);
	deleteEventParameterString = deleteEventParameterString.replace(parameter1Placeholder, QString::number(profileId));

	deleteEventString = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEEVENT, BangoConstants::GetInstance()->DATABASE_DELETEEVENT + QString::number(profileId));
	deleteProfileString = CompileQueryStatement(BangoConstants::GetInstance()->DATABASE_TABLENAMEPROFILE, BangoConstants::GetInstance()->DATABASE_DELETEPROFILE  + QString::number(profileId));
	dbBango.open();
	if(dbBango.isOpen()) {

		dbBango.transaction();
		QSqlQuery query(dbBango);

		query.exec(deleteEventParameterString);
		query.exec(deleteEventString);
		query.exec(deleteProfileString);

		const QSqlError err = query.lastError();
		if(err.isValid()) {
			qWarning() << "Error in delete transaction: " << query.lastQuery() << ". ERROR: " << err.text();
			dbBango.rollback();
			returnValue = false;
		}
		else
		{
			dbBango.commit();
			returnValue = true;
		}
		if(dbBango.isOpen()){
			dbBango.close();
		}
	}

	return returnValue;


}























